package com.summer.dingding.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiSnsGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiSnsGettokenResponse;
import com.taobao.api.ApiException;

public class DingDingUtil {

	private static String CORPID = DingDingConstants.Config.CORPID; // 企业Id
    private static String CORPSECRET = DingDingConstants.Config.CORPSECRET; // 企业应用的凭证密钥
    private static Long AGENTID = 206674255l; // 自动分配微应用的ID
    private static String LOGIN_APP_ID = DingDingConstants.Config.CodeLogin.APPID;
    private static String LOGIN_APP_SECRET = DingDingConstants.Config.CodeLogin.APP_SECRET;
    
    /**
     * 获取token
     * @return
     * @throws ApiException
     */
    public static String getAccesstoken(String appKey, String appSecret) throws ApiException {
    	DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/gettoken");
    	OapiSnsGettokenRequest request = new OapiSnsGettokenRequest();
    	request.setAppid(appKey);
    	request.setAppsecret(appSecret);
    	request.setHttpMethod("GET");
    	OapiSnsGettokenResponse response = client.execute(request);
    	
    	JSONObject json = JSONObject.parseObject(response.getBody());
    	if (null != json) {
    		if (response.isSuccess()) {
    			return json.get("access_token").toString();
    		}
    	}
    	return null;
    }
    
    /**
     * 根据企业信息获取token
     * @return
     * @throws ApiException
     */
	public static String getAppAccesstoken() throws ApiException {
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
		OapiGettokenRequest request = new OapiGettokenRequest();
		request.setCorpid(CORPID);
		request.setCorpsecret(CORPSECRET);
		request.setHttpMethod("GET");
		OapiGettokenResponse response = client.execute(request);
		
		JSONObject json = JSONObject.parseObject(response.getBody());
		if (null != json) {
			if (response.isSuccess()) {
				return json.get("access_token").toString();
			}
		}
		return null;
    }
	
	public static JSONObject ossHttpGetUtil(String url) {
		HttpGet httpGet = new HttpGet(url);
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		HttpClient httpClient = httpClientBuilder.build();
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet);
		} catch (Exception e) {
		}
		BufferedReader bufferedReader = null;
		StringBuilder entityStringBuilder = new StringBuilder();
		// 得到httpResponse的状态响应码
		int statusCode = httpResponse.getStatusLine().getStatusCode();
		JSONObject jsonObject = null;
		String access_token = "";
		if (statusCode == HttpStatus.SC_OK) {
			// 得到httpResponse的实体数据
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				try {
					return jsonObject = JSONObject.parseObject(EntityUtils
							.toString(httpEntity));
				} catch (Exception e) {

				}
			}
		}
		return null;
	}
	
	public static JSONObject ossHttpGetUtil(String url, Map<String, String> headers) {
		HttpGet httpGet = new HttpGet(url);
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		HttpClient httpClient = httpClientBuilder.build();
		HttpResponse httpResponse = null;
		if(null!=headers){
            for(Map.Entry<String,String> x:headers.entrySet()){
            	httpGet.setHeader(x.getKey(),x.getValue());
            }
        }
		try {
			httpResponse = httpClient.execute(httpGet);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		BufferedReader bufferedReader = null;
		StringBuilder entityStringBuilder = new StringBuilder();
		// 得到httpResponse的状态响应码
		int statusCode = httpResponse.getStatusLine().getStatusCode();
		JSONObject jsonObject = null;
		String access_token = "";
		if (statusCode == HttpStatus.SC_OK) {
			// 得到httpResponse的实体数据
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				try {
					return jsonObject = JSONObject.parseObject(EntityUtils
							.toString(httpEntity));
				} catch (Exception e) {

				}
			}
		}
		return null;
	}
	
	
	public static String sendHttpPost(String url, Map<String, String> headers, String body) throws Exception {
        String result = null;
        HttpClient client = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder();
        try {

            HttpPost post = new HttpPost(url);
            //设置请求头
            post.setHeader("Content-Type", "application/json");
            if(null!=headers){
                for(Map.Entry<String,String> x:headers.entrySet()){
                	post.setHeader(x.getKey(),x.getValue());
                }
            }
            StringEntity reqEntity = new StringEntity(body, "utf-8");
            reqEntity.setContentEncoding("UTF-8");
            reqEntity.setContentType("application/json");
            //设置请求体
            post.setEntity(reqEntity);
            //获取返回信息
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                entity = new BufferedHttpEntity(entity);

                InputStream in = entity.getContent();
                byte[] read = new byte[1024];
                byte[] all = new byte[0];
                int num;
                while ((num = in.read(read)) > 0) {
                    byte[] temp = new byte[all.length + num];
                    System.arraycopy(all, 0, temp, 0, all.length);
                    System.arraycopy(read, 0, temp, all.length, num);
                    all = temp;
                }
                result = new String(all,"UTF-8");
                if (null != in) {
                    in.close();
                }
            }
            return result;
        } catch (Exception e) {
            System.out.println("接口请求失败"+e.getStackTrace());
        }
        return result;
    }
}
